package com.partner.partnerback.common;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class MyFilter implements Filter {

    //以秒内 只允许通过2个请求
    private static volatile long startTime = System.currentTimeMillis();

    private static long windowTime = 1000L;

    private static final AtomicInteger bear = new AtomicInteger(0);

    private static final int door = 100;  //windowTime ms 内允许通过的请求数

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        int count = bear.incrementAndGet(); //来一个请求就加一
        if (count == 1){ // 并发安全
            startTime = System.currentTimeMillis();
        }
        long now = System.currentTimeMillis();
        if ( now - startTime <= windowTime){
            if ( count > door){//超过了赋值
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.setStatus(HttpStatus.OK.value());
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
                response.getWriter().print(JSONUtil.toJsonStr(Result.error("402","接口请求太频繁")));
                return;
            }
        }else{
            //进入下一个窗口
            startTime = System.currentTimeMillis();
            bear.set(1);
        }
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        filterChain.doFilter(servletRequest,servletResponse);
        log.info("接口请求路径，{}",request.getServletPath());
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
